package com.firword.common.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import com.firword.common.repository.mapper.SysDicMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.io.Reader;

/**
 * @author: jingyajun
 * @date: 2020/9/29
 * @description: 代替 spring-mybatis.xml
 * @since:
 */
@Configuration
@AutoConfigureAfter(DruidDataSourceAutoConfigure.class)
public class MapperConfiguration {
    @Bean
    @ConditionalOnMissingBean
    public SqlSessionFactory sqlSessionFactory() {
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader("config/mybatis.cfg.xml");
            SqlSessionFactory sqlSessionFactory = builder.build(reader);
            return sqlSessionFactory;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnBean(SqlSessionFactory.class)
    public SysDicMapper sysDicMapper(SqlSessionFactory sqlSessionFactory) {
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        return sqlSession.getMapper(SysDicMapper.class);
    }
}
